package com.nami.dispatcher.infra.impl.packet;


import com.nami.dispatcher.domain.repository.PacketFactory;
import com.nami.dispatcher.infra.property.PacketProperty;

import com.nami.gate.external.basic.request.upmsg.client.ClientResponse;

import com.nami.im.network.model.enums.DownMsgErrorCode;
import com.nami.im.network.model.packet.v2.Packet;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Service;

/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-09-25 8:50
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
@Service
@AllArgsConstructor
public class PacketFactoryImpl implements PacketFactory {

    private final PacketProperty packetProperty;


    private Packet createAndSetDefaultValue(Byte cmd) {
        Packet packet = new Packet();
        packet.setMagic((byte) 8);
        packet.setVersion((byte) packetProperty.getVersion());
//        packet.setSerial((byte) packetProperty.getSerial());
//        packet.setEncrypt((byte) packetProperty.getEncrypt());
        packet.setCmd(cmd);
        return packet;
    }

    @Override
    public Packet newPacket(Byte cmd, Object data) {
        Packet packet = createAndSetDefaultValue(cmd);
//        packet.setBody(Serializer.prototype(packet.getSerial()).serialize(data));
        packet.setBody(JsonUtils.toJsonString(data).getBytes());
        return packet;
    }

    /**
     * @return
     */
    @Override
    public Packet newPacket() {
        Packet packet = new Packet();
        packet.setMagic((byte) 8);
        packet.setVersion((byte) packetProperty.getVersion());
//        packet.setSerial((byte) packetProperty.getSerial());
//        packet.setEncrypt((byte) packetProperty.getEncrypt());
        return packet;
    }

    private Packet newDownmsgRespPacket(Byte cmd, boolean success,
                                        String code, String msg, Object body) {
        ClientResponse clientResponse = new ClientResponse();
        clientResponse.setSuccess(success);
        clientResponse.setErrCode(code);
        clientResponse.setErrMessage(msg);
        clientResponse.setData(JsonUtils.toJsonString(body));
        return this.newPacket(cmd, clientResponse);
    }

    @Override
    public Packet newDownmsgErrorRespPacket(Byte cmd, DownMsgErrorCode errorCode, Object body) {
        return this.newDownmsgRespPacket(cmd, false, errorCode.getCode(), errorCode.getMsg(), body);
    }

    @Override
    public Packet newDownmsgSuccPacket(Byte cmd, Object body) {
        ClientResponse clientResponse = ClientResponse.buildSuccess();
        clientResponse.setData(JsonUtils.toJsonString(body));
        return this.newPacket(cmd, clientResponse);
    }


}
